import { MenuModel, MenuParam } from '@/api/system/menu/MenuModel'
import { getMenuSortApi, getParentMenuApi } from '@/api/system/menu/menu'
import useInstance from '@/hooks/useInstance'
import { EditType, Title } from '@/types/BaseEnum'
import { DialogModel } from '@/types/BaseType'
import { ElForm } from 'element-plus'
import { ref, reactive } from 'vue'
import { StatusCode } from '@/http/request'

export default function useMenuAddAndEdit(
    dialogModel: DialogModel,
    onShow: any,
    onClose: any,
    addModel: MenuModel,
    emit: any
) {
    const { global } = useInstance()

    const treeData = reactive({
        data: []
    })

    // 表单ref属性
    const addMenuForm = ref<InstanceType<typeof ElForm>>()

    const onConfirm = () => {
        addMenuForm.value?.validate((valid) => {
            if (valid) {
                emit('save', addModel)
                onClose()
            }
        })
    }

    // 展示弹框
    const show = async (type: string, row?: MenuModel) => {
        await getTreeData()

        // console.log('菜单数据：', row)

        // 设置弹框的标题
        type == EditType.ADD
            ? (dialogModel.title = Title.ADD)
            : (dialogModel.title = Title.EDIT)

        // 显示弹框
        onShow()
        // 清空表单
        global.$resetForm(addMenuForm.value, addModel)
        // 把要编辑的数据，放到表单绑定的model里面
        global.$objCoppy(row, addModel)

        if (row?.type == '0') {
            dialogModel.height = 350
        } else if (row?.type == '1') {
            dialogModel.height = 400
        } else {
            dialogModel.height = 250
        }
        if (type == EditType.ADD && row) {
            await getMenuSort(row.parent_id)
        }
        console.log('dialogModel：', dialogModel)
        // 设置type
        addModel.editType = type
    }

    // 获取树的数据
    const getTreeData = async () => {
        let res = await getParentMenuApi()
        if (res && res.code == StatusCode.Success) {
            treeData.data = res.data
        }
    }

    // 获取子菜单sort最大值
    const getMenuSort = async (id: string) => {
        if (id == '') {
            id = '0'
        }
        const param = reactive<MenuParam>({
            id: id
        })
        let res = await getMenuSortApi(param)
        if (res && res.code == StatusCode.Success) {
            addModel.sort = res.data.sort + 1
        }
    }

    const sortHandleChange = (value: number) => {
        console.log(value)
    }

    const typeHandleChange = (value: number) => {
        if (value == 0) {
            dialogModel.height = 300
        } else if (value == 1) {
            dialogModel.height = 400
        } else {
            dialogModel.height = 250
        }
    }

    //选中的图标
    const select = (node: any) => {
        console.log('图标值', node)
        addModel.icon = node
    }

    return {
        onConfirm,
        show,
        sortHandleChange,
        typeHandleChange,
        addMenuForm,
        getMenuSort,
        treeData,
        select
    }
}
